<template>
  <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" @submit.native.prevent>
    <el-form-item label="学校" prop="school" class="mb-6">
      <el-input v-model="form.school" />
    </el-form-item>

    <el-form-item label="表格数据" prop="tableData">
      <el-table :data="form.tableData" border style="width: 100%">
        <!-- 姓名列 -->
        <el-table-column label="姓名" width="180">
          <template v-slot="{ $index, row }">
            <el-form-item :prop="`tableData.${$index}.name`" :rules="rules.name" class="mb-6">
              <el-input v-model="row.name" />
            </el-form-item>
          </template>
        </el-table-column>

        <!-- 年龄列 -->
        <el-table-column label="年龄" width="180">
          <template v-slot="{ $index, row }">
            <el-form-item :prop="`tableData.${$index}.age`" :rules="rules.age">
              <el-input v-model.number="row.age" />
            </el-form-item>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作">
          <template v-slot="{ $index }">
            <el-button type="danger" icon="el-icon-delete" @click="removeRow($index)" />
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <div style="margin-top: 20px">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="addRow">新增一行</el-button>
    </div>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        school: '',
        tableData: [
          { name: '', age: null },
          { name: '', age: null }
        ]
      },
      rules: {
        school: [{ required: true, message: '请输入学校', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        age: [
          { required: true, message: '请输入年龄', trigger: 'blur' },
          { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    addRow() {
      this.form.tableData.push({ name: '', age: null })
    },
    removeRow(index) {
      this.form.tableData.splice(index, 1)
    },
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          console.log('提交数据:', this.form.tableData)
          this.$message.success('校验成功')
        } else {
          // this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.el-form-item {
  margin-bottom: 24px;
}
</style>
